#include "buttondelegate.h"

#include <QApplication>
#include <QPainter>
#include <QMouseEvent>
#include <QStyleOptionButton>

static QRect ButtonRect(const QRect &rect) {
    return QRect(rect.center()-QPoint(25, 12), QSize(50, 24));
    // return rect.adjusted(1, 1, -1, -1);
}

ButtonDelegate::ButtonDelegate(const QString &text, QObject *parent)
    : QStyledItemDelegate{parent}
    , m_text {text}
{}

void ButtonDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    Q_UNUSED(index)
    QStyleOptionButton buttonOption;
    buttonOption.text = m_text;
    // buttonOption.features = QStyleOptionButton::CommandLinkButton;
    buttonOption.rect = ButtonRect(option.rect);
    buttonOption.state = option.state;

    painter->save();
    if (option.state & QStyle::State_Selected) {
        painter->fillRect(option.rect, option.palette.highlight());
        painter->setBrush(option.palette.highlightedText());
    }

    QApplication::style()->drawControl(QStyle::CE_PushButton, &buttonOption, painter);

    painter->restore();
}

bool ButtonDelegate::editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index)
{
    if(event->type() == QEvent::MouseButtonRelease) {
        QMouseEvent *mouseEvent = static_cast<QMouseEvent *>(event);
        if(ButtonRect(option.rect).contains(mouseEvent->pos()))
        {
            emit clicked(index.row());
        }
    }
    return QStyledItemDelegate::editorEvent(event, model, option, index);

}
